﻿using MRSite.Cache.Configuration;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.Cache
{
    public abstract class BaseCacheManager : ICacheManager
    {
        protected readonly ConcurrentDictionary<string, ICache> Caches;
        protected readonly ICacheConfiguration CacheConfiguration;

        protected BaseCacheManager(ICacheConfiguration cacheConfiguration)
        {
            Caches = new ConcurrentDictionary<string, ICache>();
            CacheConfiguration = cacheConfiguration;
        }

        public void Dispose()
        {
            //foreach(var item in Caches)
            //{
            //    item.Value.Dispose();
            //}
            Caches.Clear();
        }

        public virtual ICache GetCache(string name)
        {
            if (name is null)
            {
                throw new ArgumentException(nameof(name));
            }
            return Caches.GetOrAdd(name, (cacheName) =>
            {
                var cache = CreateCacheImplement(cacheName);
                var configurationItems = CacheConfiguration.ConfigurationItems.Where(item =>
                {
                    return item.CacheName == null || item.CacheName == cacheName;
                });
                foreach(var item in configurationItems)
                {
                    item.ActionInitCache?.Invoke(cache);
                }

                return cache;
            });
        }

        protected abstract ICache CreateCacheImplement(string cacheName);

        public IReadOnlyList<ICache> GetCaches()
        {
            return Caches.Values.ToImmutableList();
        }
    }
}
